package com.yihaodian.index;

import java.util.concurrent.ExecutorService;

import org.apache.log4j.Logger;

import com.google.inject.Inject;
import com.yihaodian.api.search.SearchException;
import com.yihaodian.index.meta.shard.Shard;
import com.yihaodian.indices.IndicesService;
import com.yihaodian.search.broker.ThreadPools;
import com.yihaodian.search.broker.shard.ShardIndexRequest;
import com.yihaodian.search.broker.shard.ShardIndexService;
import com.yihaodian.server.LifeCycleService;

public class LocalIndexService implements ShardIndexService, LifeCycleService {
	static Logger logger = Logger.getLogger(LocalIndexService.class);

	IndicesService indicesService;

	@Inject
	public LocalIndexService(IndicesService indicesService) {
		this.indicesService = indicesService;
	}

	@Override
	public void startup() {
		logger.info("IndexService startup");
	}

	@Override
	public void shutdown() {
	}

	@Override
	public void index(final ShardIndexRequest request) throws SearchException {
		try {
			Shard shard = new Shard(request.getIndexRequest().getIndexName(),
					request.getShardId());

			final IndexShard indexShard = indicesService.getIndexShard(shard
					.getShardId());
			if (indexShard == null) {
				throw new SearchException("IndexShard not start yet " + shard);
			}

			ExecutorService es = ThreadPools.getThreadPool(ThreadPools.INDEX);
			es.submit(new Runnable() {

				@Override
				public void run() {
					try {
						indexShard.getIndexer().index(request.indexRequest);
					} catch (Exception e) {
						logger.error(request.getIndexRequest().getIndexName()
								+ " " + request.getShardId(), e);
					}
				}
			});

		} catch (Exception e) {
			throw new SearchException(e);
		}
	}
}
